<?php


// 将数据格式化为逗号分隔值，从而可以由电子表格或数据库导入

$sales = [
    ['Northeast', '2005-01-01', '2005-02-01', 12.54],
    ['Northwest', '2005-01-01', '2005-02-01', 546.33],
    ['Southeast', '2005-01-01', '2005-02-01', 93.26],
    ['Southwest', '2005-01-01', '2005-02-01', 945.21],
    ['All Regions', '--', '--', 1597.34],
];


$filename = './sales.csv';

// 写入
//$fh = fopen($filename, 'w') or die('can\' open ' . $filename);

/******  通过 php://output 输出   *****/


$fh = fopen('php://output', 'w') or die('can\' open php://output');
foreach ($sales as $line) {
    if (fputcsv($fh, $line) === false) {
        die("can't write CSV line");
    }
}
fclose($fh) or die("can't close php://output");


/******** 把结果让入字符串中，可以结合输出缓冲  ************/

ob_start();
$fh = fopen('php://output', 'w') or die('can\' open php://output');
foreach ($sales as $line) {
    if (fputcsv($fh, $line) === false) {
        die("can't write CSV line");
    }
}
fclose($fh) or die("can't close php://output");
$output = ob_get_contents();
ob_end_clean();
var_dump($output);



